package com.pavelk.orion.utils
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.filters.BlurFilter;
	import flash.filters.GlowFilter;
	import flash.geom.ColorTransform;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	/**
	* Blurs a background (MovieClip or Sprite) behind a transparent window (MovieClip or Sprite).
	*
	* @author Pavel Krusek
	*/	
	public class WindowBlur
	{
		private var background:DisplayObjectContainer;
		private var window    :DisplayObjectContainer;
 
		private var blurredImageData:BitmapData;
		private var blurredImage    :Bitmap;
		private var mask            :DisplayObjectContainer;
		private var _blurAmount     :int;
 
		private var blur :BlurFilter;
		private var point:Point = new Point();
		
		public function WindowBlur( background:DisplayObjectContainer, 
									window:DisplayObjectContainer,
									w:Number,
									h:Number, 
									blurAmount:int = 6  )
		{
			this.background = background;
			this.window = window;
			this.window.width = w;
			this.window.height = h;
			_blurAmount = ( blurAmount >= 0 && blurAmount <= 255 ) ? blurAmount : 16;
			blur = new BlurFilter( this.blurAmount, this.blurAmount, 3 );
 			
 			var ct:ColorTransform = new ColorTransform();
			ct.color = 0xff0000;
			//window.transform.colorTransform = ct;

			window.alpha = 1;
 			
 			
			initBlur();
			initMask();
		}
		
		private function initBlur() : void 
		{
			blurredImageData = new BitmapData( background.width, background.height, false );
			blurredImageData.draw( background );
			blurredImageData.applyFilter( blurredImageData, blurredImageData.rect, point, blur);
			//var glow:GlowFilter = new GlowFilter( 0xFFFFFF, 1, 3, 3, 2, 1, false, false );
			//blurredImageData.applyFilter( blurredImageData, blurredImageData.rect, point, glow);
			blurredImage = new Bitmap( blurredImageData );
 			
			background.addChild( blurredImage );
		}
		
		private function initMask() : void 
		{
			var MaskClass:Class = Object( window ).constructor;
			mask = new MaskClass();
			mask.filters = window.filters;
			blurredImage.mask = mask;
			mask.visible = false;
 
			window.addChildAt( mask, 0 );
		}
		
		private function update() : void 
		{
			background.removeChild( blurredImage );
			blurredImageData.dispose();
			initBlur();
			blurredImage.mask = mask;
		}
		
		public function kill() : void 
		{
			background.removeChild( blurredImage );
			window.removeChild( mask );
 
			blurredImageData.dispose();
 
			blurredImage = null;
			blurredImageData = null;
			mask = null;
			blur = null;
		}
		
		public function get blurAmount():int { return _blurAmount; }
 
		public function set blurAmount( value:int ) : void 
		{
			_blurAmount = value;
			blur.blurX = blur.blurY = _blurAmount;
			update();
		}

	}
}
